package io.xdag.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import io.xdag.utils.AssertUtils;

public class XdagFile {

	private String path;

	private static final String MODE_RW = "rw";

	// private static final String MODE_RB = "rb";

	public XdagFile() {
	}

	public XdagFile(String path) {
		this.path = path;
	}

	public Byte[] readFile() {
		return this.readFile(this.path);
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	public boolean exists(String filePath) {
		Path path = java.nio.file.Paths.get(filePath);
		return java.nio.file.Files.exists(path, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
	}

	/**
	 * 读取文件返回Byte[]
	 * 
	 * @return
	 */
	public Byte[] readFile(String path) {

		RandomAccessFile raFile;
		List<Byte> byteList = new ArrayList<Byte>();
		Byte[] bytes = null;
		try {
			AssertUtils.isNull(path);
			raFile = new RandomAccessFile(path, MODE_RW);
			FileChannel inChannel = raFile.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(512);
			int bytesRead = inChannel.read(buf);

			while (bytesRead != -1) {
				System.out.println("Read:" + bytesRead);
				buf.flip();
				while (buf.hasRemaining()) {
					byteList.add(buf.get());
				}
				buf.clear();
				bytesRead = inChannel.read(buf);
			}
			bytes = byteList.toArray(new Byte[byteList.size()]);
			raFile.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return bytes;
	}

	/**
	 * 写入文件
	 * 
	 * @param path
	 *            文件路径
	 * @param buf
	 *            文件buf
	 */
	public void writeFile(String path, ByteBuffer buf) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(path));
			FileChannel channel = fos.getChannel();
			// 字节缓冲的容量和limit会随着数据长度变化，不是固定不变的
			System.out.println("初始化容量和limit：" + buf.capacity() + "," + buf.limit());
			int length = 0;

			while ((length = channel.write(buf)) != 0) {
				System.out.println("写入长度:" + length);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}
